<template>
  <el-dialog :title="title || `${form.patTaskId ? '修改' : '添加'}任务`" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="800px" @closed="closed">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="projectId" class="hide" />
      <el-form-item prop="patTaskId" class="hide" />
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="巡更类型" prop="patrolTypeId" style="height: 36px">
            <span slot="label">
              巡更类型
              <el-tooltip placement="top" content="更改巡更类型将会清除点位列表">
                <i class="el-icon-warning-outline" />
              </el-tooltip>
            </span>
            <treeselect
              v-model="form.patrolTypeId"
              :options="patTypeTree"
              :normalizer="patTypeNormalizer"
              disable-branch-nodes
              show-count
              placeholder="请选择巡更类型"
              :disabled="isEdit"
              @select="onChangePatrolTypeId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName"><el-input v-model.trim="form.taskName" placeholder="请输入任务名称" :maxlength="100" :disabled="patCfgLoading" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务开始时间" prop="taskBeginDate">
            <el-date-picker v-model="form.taskBeginDate" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm:ss" :clearable="false" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务结束时间" prop="taskEndDate">
            <el-date-picker v-model="form.taskEndDate" type="datetime" placeholder="选择时间" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :maxlength="255" /></el-form-item>
    </el-form>

    <EditSpot ref="EditSpot" :patrol-type-id="form.patrolTypeId" />

    <div slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 添加或修改巡更任务
import moment from 'moment'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { nameRule } from '@/utils/validate'
import { flatList2tree } from '@/utils'
import { editFormMixin } from '@/utils/mixin'
import { listPatType, listPatCfg, addTask, setTask, saveBatchTaskSpot } from '@/api/cq/patrol'
import EditSpot from './EditTaskSpot'
export default {
  components: { Treeselect, EditSpot },
  mixins: [editFormMixin],
  props: { title: { type: String, default: '' } },
  data() {
    return {
      primaryKey: 'patTaskId',
      addApi: addTask,
      updateApi: setTask,
      form: {
        projectId: '',
        patTaskId: '',
        patrolTypeId: null,
        taskName: '',
        taskBeginDate: '',
        taskEndDate: '',
        remark: '',
        status: 0,
        taskType: '3'
      },
      rules: {
        patrolTypeId: [{ required: true, message: '请选择巡更类型' }],
        taskName: [{ required: true, message: '请输入任务名称' }, nameRule],
        taskBeginDate: [
          { required: true, message: '请选择任务开始时间' },
          {
            validator: (rule, val, cb) => {
              const eTime = this.form.taskEndDate
              eTime && this.$refs.form.validateField('taskEndDate')
              cb()
            }
          }
        ],
        taskEndDate: [
          {
            validator: (rule, val, cb) => {
              // null 设为空字符串
              if (val === null) this.form.taskEndDate = ''
              const sTime = this.form.taskBeginDate
              // 结束时间选填
              if (!val || !sTime) return cb()
              if (moment(sTime).isAfter(moment(val))) return cb('结束时间不能小于开始时间')
              cb()
            }
          }
        ]
      },
      patTypeLoading: false,
      patTypeTree: [],
      patCfgLoading: false
    }
  },
  computed: {
    isEdit() {
      return !!this.form.patTaskId
    }
  },
  methods: {
    closed() {
      this.$refs.form.resetFields()
      this.$refs.EditSpot.reset()
    },
    async opened(item = {}) {
      this.getPatTypeList()

      this.$refs.EditSpot.init({ projectId: item.projectId, patTaskId: item.patTaskId || '' })
    },
    async getPatTypeList() {
      this.patTypeLoading = true
      const res = await listPatType().catch(() => false)
      this.patTypeLoading = false
      if (res === false) return

      let data = res.data || []
      data = flatList2tree(data, { id: 'patTypeId' })
      this.patTypeTree = data
    },
    patTypeNormalizer(node) {
      if (!node.children?.length) delete node.children
      return { id: node.patTypeId, label: node.patTypeName, children: node.children }
    },
    async onChangePatrolTypeId() {
      this.$refs.EditSpot.clearList()
      const { patrolTypeId } = this.form
      if (!patrolTypeId) return

      const opt = { patrolTypeId, pageSize: 1 }
      this.patCfgLoading = true
      const res = await listPatCfg(opt).catch(() => false)
      this.patCfgLoading = false
      if (res === false) return

      const data = res.rows?.[0] || {}
      if (!data.patCfgId) return

      // 自动填入配置字段
      this.form.taskName = data.planName
    },
    async addTask() {
      const spots = this.$refs.EditSpot.getData()
      if (!spots.length) return this.msgInfo('请添加点位')

      const opt = { ...this.form }
      this.btnLoading = true
      const res = await addTask(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      const patTaskId = res.data?.patTaskId
      if (!patTaskId) return this.msgError('数据返回有误，缺少任务ID')

      const opt2 = spots.map(i => ({
        projectId: opt.projectId,
        patTaskId,
        patSpotId: i.patSpotId,
        seq: i.seq || 0
      }))
      this.btnLoading = true
      const res2 = await saveBatchTaskSpot(opt2).catch(() => false)
      this.btnLoading = false
      if (res2 === false) return

      this.msgSuccess('新增成功')
      this.show = false
      this.$emit('ok')
    },
    async onSubmit() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return

      if (!this.isEdit) return this.addTask()

      const opt = { ...this.form }
      this.btnLoading = true
      const res = await setTask(opt).catch(() => false)
      this.btnLoading = false
      if (res === false) return

      this.msgSuccess('提交成功')
      this.show = false
      this.$emit('ok')
    }
  }
}
</script>
